// pages/approve/approve.js

import { createStoreBindings } from 'mobx-miniprogram-bindings';
import { store } from '../../store/store';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    option1: [
      { text: '全部', value: 0 },
      { text: '未通过', value: 1 },
      { text: '已通过', value: 2 },
    ],
    option2: [
      { text: '默认排序', value: 'a' },
      { text: '时间升序', value: 'b' },
      { text: '时间降序', value: 'c' },
      { text: '账号升序', value: 'd' },
      { text: '账号降序', value: 'e' },
    ],
    value1: 0,
    value2: 'a',
    datas: [],
    currentPage: 0,
    urlGetImage: '/portal/user/getUploadedApprove/',
    urlGetApproveNextPage: '/portal/approve/getPage/',
    urlAccept: '/portal/approve/accept',
    urlRefuse: '/portal/approve/refuse',
    urlCallBack: '/portal/approve/callBack',
  },

  getInfo() {
    Toast.loading({
      duration: 0,
      message: '加载中...',
      forbidClick: true,
      loadingType: 'spinner',
    });

    let newDatas = this.data.datas;
    let page = this.data.currentPage + 1
    wx.request({
      url: this.data.urlGetApproveNextPage + page + "/" + this.data.value1 + "/" + this.data.value2,
      method: "GET",
      success: (res) => {
        Toast.clear();
        if (res.data.data.length == 0) {
          Toast.clear(),
          Toast('没有更多数据了');
          return;
        }

        for (const key in res.data.data) {
          let date = this.formatDate(res.data.data[key].infoDate);
          res.data.data[key].infoDate = date;
          let images = this.getUrlByStr(res.data.data[key].images);
          res.data.data[key].images = images;
          newDatas.push(res.data.data[key]);
        }
        this.setData({
          currentPage: page,
          datas: newDatas,
        })
      },
    })
  },

  getUrlByStr(s) {
    let images = s.split(',');
    for (let i = 0; i < images.length; i++) {
      images[i] = this.data.urlGetImage + images[i];
    }
    return images;
  },

  formatDate (time) {
    var date = new Date(time);
    var year = date.getFullYear(); //年份
    var month = date.getMonth() + 1; //月份
    var day = date.getDate(); //日
    var hour = function () { //获取小时
        return date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    }
    var minute = function () { //获取分钟
        return date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    }

    var second = function () { //获取秒数
        return date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    }
    return year + '-' + month + '-' + day + ' ' + hour() + ':' + minute() + ':' + second()
  },

  previewImg(e) {
    let imgUrls = e.currentTarget.dataset.urls;
    wx.previewImage({
      urls: imgUrls,
      success: (res) => {
        console.log("success!");
      },
    })
  },

  onChange1(e) {
    console.log(e.detail);
    // 只要更改内容显示方式，就从第1页开始查
    this.setData({
      datas: [],
      currentPage: 0,
      value1: e.detail,
    })

    this.getInfo();
  },

  onChange2(e) {
    console.log(e.detail);
    // 只要更改内容显示方式，就从第1页开始查
    this.setData({
      datas: [],
      currentPage: 0,
      value2: e.detail,
    })

    this.getInfo();
  },

  wantToAccept(e) {
    let id = e.currentTarget.dataset.id;
    // console.log(id);

    Dialog.confirm({
      message: '确认 ' + id + ' 审核成功？',
    })
      .then(() => {
        // on confirm
        // console.log(this.data.user.id);
        wx.request({
          url: this.data.urlAccept,
          method: "POST",
          data: {
            userId: id,
            managerId: this.data.user.id,
          },
          headers: {
            'Content-Type': 'application/json'  // 从请求体发送json对象
          },
          success: (result) => {
            Toast(result.data.msg);
            this.setData({
              currentPage: 0,
              datas: [],
            });
            this.getInfo();
          }
        })
      })
      .catch(() => {
        // on cancel
      });
  },

  wantToRefuse(e) {
    let id = e.currentTarget.dataset.id;

    Dialog.confirm({
      message: '确认 ' + id + ' 审核失败？',
    })
      .then(() => {
        // on confirm
        wx.request({
          url: this.data.urlRefuse,
          method: "POST",
          data: {
            userId: id,
            managerId: this.data.user.id,
          },
          headers: {
            'Content-Type': 'application/json'  // 从请求体发送json对象
          },
          success: (result) => {
            Toast(result.data.msg);
            this.setData({
              currentPage: 0,
              datas: [],
            });
            this.getInfo();
          }
        })
      })
      .catch(() => {
        // on cancel
      });
  },

  wanToCallBack(e) {
    let id = e.currentTarget.dataset.id;
    // console.log(id);

    Dialog.confirm({
      message: '确认驳回 ' + id + ' 的认证？',
    })
      .then(() => {
        // on confirm
        // console.log(this.data.user.id);
        wx.request({
          url: this.data.urlCallBack,
          method: "POST",
          data: {
            userId: id,
            managerId: this.data.user.id,
          },
          headers: {
            'Content-Type': 'application/json'  // 从请求体发送json对象
          },
          success: (result) => {
            Toast(result.data.msg);
            this.setData({
              currentPage: 0,
              datas: [],
            });
            this.getInfo();
          }
        })
      })
      .catch(() => {
        // on cancel
      });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 挂载全局数据
    this.storeBindings = createStoreBindings(this, {
      store,
      fields: ['user'],
      actions: ['getUser', 'getWebsite']
    });

    this.setData({
      urlGetImage: this.getWebsite() + this.data.urlGetImage,
      urlGetApproveNextPage: this.getWebsite() + this.data.urlGetApproveNextPage,
      urlAccept: this.getWebsite() + this.data.urlAccept,
      urlRefuse: this.getWebsite() + this.data.urlRefuse,
      urlCallBack: this.getWebsite() + this.data.urlCallBack,
    })

    this.getInfo();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      currentPage: 0,
      datas: [],
    });
    this.getInfo();
    Toast.clear();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.getInfo();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})